package com.int_tech.timeTask185;

import com.int_tech.MessageCodeAll.dao.CodeA0NewDao;
import com.int_tech.MessageCodeAll.dao.CodeA2DoubleDao;
import com.int_tech.MessageCodeAll.entity.CodeA0;
import com.int_tech.MessageCodeAll.entity.CodeA0New;
import com.int_tech.MessageCodeAll.entity.CodeA2Double;
import com.int_tech.car.dao.CarDao;
import com.int_tech.car.entity.Car;
import com.int_tech.control.dao.SocketLogSendDao;
import com.int_tech.control.entity.SocketLog;
import com.int_tech.control.entity.SocketLogSend;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.utils.DateTool;
import com.int_tech.utils.HttpClient;
import com.int_tech.utils.TimePlus;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by liubochao on 2018/7/25.
 */
@Component
public class MessionToJDTimeTask {

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private SocketLogSendDao socketLogSendDao;

    @Autowired
    private CarDao carDao;

    @Autowired
    private CodeA0NewDao codeA0NewDao;

    @Autowired
    private CodeA2DoubleDao codeA2DoubleDao;


    /**
     * 任务单匹配单点体积
     */
    @Scheduled(cron="0 0/5 * * * ?")
    public void checkEveryCountForVolumeToMession(){

        //每次遍历100条
        PageRequest pageRequest = new PageRequest(0, 100);
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndCarNumber(pageRequest, 0,"010ACJ383");
        Page<Mession> messionPage = messionDao.findByIsAnsyCarTime(pageRequest, 5);
        List<Mession> messionList = messionPage.getContent();


        for(Mession mession : messionList)
        {

            try
            {
                List<CodeA0New> codeA0NewList = codeA0NewDao.findByRateDateStringAndCheckStatus(mession.getRateDataString(),2);

                if(codeA0NewList != null && codeA0NewList.size() != 0)
                {
                    CodeA0New codeA0New = codeA0NewList.get(0);
                    mession.setEveryRate(codeA0New.getEveryRate());
                    mession.setIsAnsyCarTime(6);
                    messionDao.save(mession);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                mession.setIsAnsyCarTime(-6);
                messionDao.save(mession);
            }
        }


    }



    /**
     * 每一个点的体积计算
     */
    @Scheduled(cron="0 0/5 * * * ?")
    public void checkEveryCountForVolume(){

        //每次遍历100条
        PageRequest pageRequest = new PageRequest(0, 1000);
        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndStatus(pageRequest, 2,0);
        List<CodeA0New> codeA0NewList = codeA0NewPage.getContent();

        for(CodeA0New codeA0New : codeA0NewList)
        {
            codeA0New.setStatus(1);
            codeA0NewDao.save(codeA0New);


            try
            {

                String logData = codeA0New.getDataString();

                String[] logs = logData.split(",");


                //长宽高
                float x = Float.parseFloat(logs[10]);
                float y = Float.parseFloat(logs[11]);
                float z = Float.parseFloat(logs[12]);

          /*  x = x/100;
            y = y/100;
            z = z/100;*/



                //行列
                int hang = Integer.parseInt(logs[13]);
                int lie = Integer.parseInt(logs[14]);

                //行列间距
                int hangjianju = Integer.parseInt(logs[15]);
                int liejianju = Integer.parseInt(logs[16]);

                //前后
                int qian = Integer.parseInt(logs[17]);
                int hou = Integer.parseInt(logs[18]);

                //左右
                int zuo = Integer.parseInt(logs[19]);
                int you = Integer.parseInt(logs[20]);


                //特殊点位置
                //右上角点,一定是第一点
                int pointysj = 21;
                //左上角点，为第一点+行数-1
                int pointzsj = 20+hang;
                //左下角点，为最后一个点
                int pointzxj = logs.length-1;
                //右下角点，为最后一个点-行数+1
                int pointyxj = logs.length-hang;
                //左右第二列
                int pointz2l = 0;
                int pointy2l = 0;
                //左右第三列
                int pointz3l = 0;
                int pointy3l = 0;



                //所有特殊点位,根据列判断
                if(lie == 2)
                {
                    //如果是两列，没有最中间点，全是周围点
                }
                else if(lie == 3)
                {
                    //中间有一列
                    pointz3l = pointyxj-1;
                    pointy3l = pointzsj+1;
                }
                else if(lie == 4)
                {
                    //中间有两列
                }

                double rateTotal = 0;
                double total = x*y*z;
                double rate = 0;
                String rateString = "";
                String rateEvery = "";
                int totalArea = 0;
                int totalCount = 0;

                int a1 = 0;
                int a2 = 0;
                int a3 = 0;
                int a4 = 0;

                int isFull = 1;

                //如果isFull为1，证明有货
                if(isFull == 1)
                {
                    String buchang = "";

                    for(int i=21;i<21+hang*lie;i++)
                    {
                        int h = Integer.parseInt(logs[i]);
                        if("9999".equals(logs[i]))
                        {
                            //9999做补偿
                            logs[i] = buchang;
                        }
                        else
                        {
                            buchang = logs[i];
                        }
                        try
                        {
                            totalCount++;
                            //传感器面积
                            int area = 0;

                            //四个角上的点
                            if(i == pointysj||i == pointzsj||i == pointzxj||i == pointyxj)
                            {
                                area = (hangjianju/2+zuo)*(liejianju/2+qian)*h;
                                if(StringUtils.isEmpty(rateEvery))
                                {
                                    rateEvery += String.valueOf(area);
                                }
                                else
                                {
                                    rateEvery += "," + String.valueOf(area);
                                }
                            }
                            else if(i == pointz3l||i == pointy3l)
                            {
                                //中间两头的点
                                area = hangjianju*(hangjianju/2+qian)*h;
                                if(StringUtils.isEmpty(rateEvery))
                                {
                                    rateEvery += String.valueOf(area);
                                }
                                else
                                {
                                    rateEvery += "," + String.valueOf(area);
                                }
                            }
                            else if(i > 21&&i < (20+hang))
                            {
                                //第一行中间
                                area = hangjianju*(hangjianju/2+zuo)*h;
                                if(StringUtils.isEmpty(rateEvery))
                                {
                                    rateEvery += String.valueOf(area);
                                }
                                else
                                {
                                    rateEvery += "," + String.valueOf(area);
                                }
                            }
                            else if(i > logs.length-hang&&i < logs.length-1)
                            {
                                //最后一行中间
                                area = hangjianju*(hangjianju/2+zuo)*h;
                                if(StringUtils.isEmpty(rateEvery))
                                {
                                    rateEvery += String.valueOf(area);
                                }
                                else
                                {
                                    rateEvery += "," + String.valueOf(area);
                                }
                            }
                            else
                            {
                                //最中间
                                area = hangjianju * liejianju*h;
                                if(StringUtils.isEmpty(rateEvery))
                                {
                                    rateEvery += String.valueOf(area);
                                }
                                else
                                {
                                    rateEvery += "," + String.valueOf(area);
                                }
                            }

                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }

                    codeA0New.setEveryRate(rateEvery);
                    codeA0NewDao.save(codeA0New);
                }
            }
            catch (Exception e)
            {
                codeA0New.setStatus(-1);
                codeA0NewDao.save(codeA0New);
                e.printStackTrace();
            }
        }
    }



    //任务单toJD
    @Scheduled(cron="0 0/5 * * * ?")
    public void checkMessionToJDNew(){

        PageRequest pageRequest = new PageRequest(0, 1000);
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndCarNumber(pageRequest, 0,"010ACJ383");
        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByStatus(pageRequest,1);
        List<CodeA0New> codeA0NewList = codeA0NewPage.getContent();

        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        for(CodeA0New codeA0New : codeA0NewList) {

            codeA0New.setStatus(3);
            codeA0NewDao.save(codeA0New);


            //如果是开门测量直接发送
            if(codeA0New.getDataString().startsWith("A01"))
            {
                try {
                    sendA0MessageToJDOpenDoor(codeA0New);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    codeA0New.setStatus(-3);
                    codeA0NewDao.save(codeA0New);
                }

            }
            else
            {
                try {

                    //查询前后开关门信息
                    PageRequest pageRequest1 = new PageRequest(0, 1);
                    Page<CodeA2Double> codeA2DoublePage = codeA2DoubleDao.findByctBeforeAndOpenStatusAndTimePlus(codeA0New.getCarNumber(), codeA0New.getCreatedTime(), 1, 180, pageRequest1);
                    List<CodeA2Double> codeA2DoubleList2 = codeA2DoublePage.getContent();

                    //之前的关门
                    CodeA2Double codeA2DoubleClose = codeA2DoubleList2.get(0);

                    //判定这个关门数据前一条的开门数据
                    codeA2DoublePage = codeA2DoubleDao.findByctAfterAndOpenStatus(codeA0New.getCarNumber(), codeA0New.getCreatedTime(), 0, pageRequest1);
                    codeA2DoubleList2 = codeA2DoublePage.getContent();

                    if (codeA2DoubleList2 == null || codeA2DoubleList2.size() == 0) {
                        //这表示这次测量的下一次开关门还没来
                        codeA0New.setStatus(2);
                        codeA0NewDao.save(codeA0New);
                        continue;
                    } else {
                        CodeA2Double codeA2DoubleOpen = codeA2DoubleList2.get(0);
                        //如果都有了，开始推送
                        sendA0MessageToJD(codeA0New, codeA2DoubleClose, codeA2DoubleOpen);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    codeA0New.setStatus(-3);
                    codeA0NewDao.save(codeA0New);
                }
            }
        }
    }

    private void sendA0MessageToJDOpenDoor(CodeA0New codeA0New) {

        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        Car car = carDao.findByCarNumberAndIsDel(codeA0New.getCarNumber(),0);

        String[] datalog = codeA0New.getDataString().split(",");
        try
        {
            for(int m = 0;m<2;m++)
            {

                int c = (int) (899999999*Math.random()+100000000);

                JSONObject jsonObject = new JSONObject();

                if(m == 0)
                {
                    jsonObject.put("type",1);
                    jsonObject.put("businessCode",c);
                    codeA0New.setCloseNumber(String.valueOf(c));
                    codeA0NewDao.save(codeA0New);

                    String stringDate = DateTool.Date2String(codeA0New.getCreatedTime(),"yyyy-MM-dd HH:mm:ss");
                    jsonObject.put("gatherTime", stringDate);

                    jsonObject.put("lat",codeA0New.getLat());
                    jsonObject.put("lng",codeA0New.getLng());
                }
                else
                {
                    break;

                    /*jsonObject.put("type",2);
                    jsonObject.put("businessCode",c);
                    codeA0New.setOpenNumber(String.valueOf(c));
                    codeA0NewDao.save(codeA0New);

                    String stringDate = DateTool.Date2String(codeA2DoubleOpen.getCreatedTime(),"yyyy-MM-dd HH:mm:ss");
                    jsonObject.put("gatherTime", stringDate);

                    jsonObject.put("lat",codeA2DoubleOpen.getLat());
                    jsonObject.put("lng",codeA2DoubleOpen.getLng());*/
                }


                jsonObject.put("vehicleNumber",car.getCarCnumber());

                jsonObject.put("dataSource","23");

                jsonObject.put("vehicleLong",Double.parseDouble(car.getLength()));
                jsonObject.put("vehicleWidth",Double.parseDouble(car.getWidth()));
                jsonObject.put("vehicleHeight",Double.parseDouble(car.getHeight()));

                //计算体积
                Double tj = (Double.parseDouble(car.getLength())*Double.parseDouble(car.getWidth())*Double.parseDouble(car.getHeight())*Double.parseDouble(codeA0New.getRate()))/100;

                BigDecimal b = new BigDecimal(tj);
                double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

                jsonObject.put("volume",String.valueOf(f1));

                //每一个点的量坊
                //行列
                int hang = Integer.parseInt(datalog[13]);
                int lie = Integer.parseInt(datalog[14]);

                String[] everyRate = codeA0New.getEveryRate().split(",");

                int hangs = 1;
                int lies = 1;

                JSONArray jsonArray1 = new JSONArray();


                for(int i = 1; i < everyRate.length+1;i++)
                {
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("position",String.valueOf(3-lies)+"-"+String.valueOf(hang+1-hangs));
                    if(lies == 2)
                    {
                        jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[hang-hangs])/10));
                    }
                    else
                    {
                        jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[(lie*hang)-hangs])/10));
                    }

                    if(i % hang == 0)
                    {
                        hangs = 1;
                        lies ++;
                    }
                    else
                    {
                        hangs ++;
                    }

                    jsonArray1.add(jsonObject2);
                }

                jsonObject.put("vehicleBoxDetailDtoList",jsonArray1.toString());

                jsonObject.put("rowNumber",lie);
                jsonObject.put("colNumber",hang);

                String sss = "jdtms";

                JSONArray jsonArray = new JSONArray();

                jsonArray.add(jsonObject);
                jsonArray.add(sss);


                String param_json = jsonArray.toString();
                String method = "jingdong.tms.data.receiveVehicleBox";
                String version ="2";
                SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String timestamp = format0.format(new Date());
                String sign = buildSign(timestamp, version, method, param_json, token, app_key, app_secret);
                System.out.println(sign);
                timestamp = URLEncoder.encode(timestamp, "utf-8");
                String url = "https://api.jdwl.com/routerjson?access_token="+token+"&app_key="+app_key+"&method="+method+"&sign="+sign+"&timestamp="+timestamp+"&v="+version+"";
                System.out.println(url);
                System.out.println(param_json);
                String response = HttpClient.post(url, param_json);
                System.out.println(response);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            codeA0New.setCheckStatus(-7);
            codeA0NewDao.save(codeA0New);
        }
    }


    //任务单toJD第二次补全
    @Scheduled(cron="0 0/7 * * * ?")
    public void checkMessionToJDNewSecond(){

        PageRequest pageRequest = new PageRequest(0, 1000);
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndCarNumber(pageRequest, 0,"010ACJ383");
        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByStatus(pageRequest,2);
        List<CodeA0New> codeA0NewList = codeA0NewPage.getContent();

        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        for(CodeA0New codeA0New : codeA0NewList) {

            if(codeA0New.getDataString().startsWith("A01"))
            {
                continue;
            }

            codeA0New.setStatus(3);
            codeA0NewDao.save(codeA0New);
            try {

                //查询前后开关门信息
                PageRequest pageRequest1 = new PageRequest(0, 1);
                Page<CodeA2Double> codeA2DoublePage = codeA2DoubleDao.findByctBeforeAndOpenStatusAndTimePlus(codeA0New.getCarNumber(), codeA0New.getCreatedTime(), 1, 180, pageRequest1);
                List<CodeA2Double> codeA2DoubleList2 = codeA2DoublePage.getContent();

                //之前的关门
                CodeA2Double codeA2DoubleClose = codeA2DoubleList2.get(0);

                //判定这个关门数据前一条的开门数据
                codeA2DoublePage = codeA2DoubleDao.findByctAfterAndOpenStatus(codeA0New.getCarNumber(), codeA0New.getCreatedTime(), 0, pageRequest1);
                codeA2DoubleList2 = codeA2DoublePage.getContent();

                if (codeA2DoubleList2 == null || codeA2DoubleList2.size() == 0) {
                    //这表示这次测量的下一次开关门还没来
                    codeA0New.setStatus(2);
                    codeA0NewDao.save(codeA0New);
                    continue;
                } else {
                    CodeA2Double codeA2DoubleOpen = codeA2DoubleList2.get(0);
                    //如果都有了，开始推送
                    sendA0MessageToJD(codeA0New, codeA2DoubleClose, codeA2DoubleOpen);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                codeA0New.setStatus(-3);
                codeA0NewDao.save(codeA0New);
            }
        }
    }

    private void sendA0MessageToJD(CodeA0New codeA0New, CodeA2Double codeA2DoubleClose, CodeA2Double codeA2DoubleOpen) {
        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        Car car = carDao.findByCarNumberAndIsDel(codeA0New.getCarNumber(),0);

        String[] datalog = codeA0New.getDataString().split(",");
        try
        {
            for(int m = 0;m<2;m++)
            {

                int c = (int) (899999999*Math.random()+100000000);

                JSONObject jsonObject = new JSONObject();

                if(m == 0)
                {
                    jsonObject.put("type",2);
                    jsonObject.put("businessCode",c);
                    codeA0New.setCloseNumber(String.valueOf(c));
                    codeA0NewDao.save(codeA0New);

                    String stringDate = DateTool.Date2String(codeA2DoubleClose.getCreatedTime(),"yyyy-MM-dd HH:mm:ss");
                    jsonObject.put("gatherTime", stringDate);

                    jsonObject.put("lat",codeA2DoubleClose.getLat());
                    jsonObject.put("lng",codeA2DoubleClose.getLng());
                }
                else
                {
                    break;

                    /*jsonObject.put("type",2);
                    jsonObject.put("businessCode",c);
                    codeA0New.setOpenNumber(String.valueOf(c));
                    codeA0NewDao.save(codeA0New);

                    String stringDate = DateTool.Date2String(codeA2DoubleOpen.getCreatedTime(),"yyyy-MM-dd HH:mm:ss");
                    jsonObject.put("gatherTime", stringDate);

                    jsonObject.put("lat",codeA2DoubleOpen.getLat());
                    jsonObject.put("lng",codeA2DoubleOpen.getLng());*/
                }


                jsonObject.put("vehicleNumber",car.getCarCnumber());

                jsonObject.put("dataSource","23");

                jsonObject.put("vehicleLong",Double.parseDouble(car.getLength()));
                jsonObject.put("vehicleWidth",Double.parseDouble(car.getWidth()));
                jsonObject.put("vehicleHeight",Double.parseDouble(car.getHeight()));

                //计算体积
                Double tj = (Double.parseDouble(car.getLength())*Double.parseDouble(car.getWidth())*Double.parseDouble(car.getHeight())*Double.parseDouble(codeA0New.getRate()))/100;

                BigDecimal b = new BigDecimal(tj);
                double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

                jsonObject.put("volume",String.valueOf(f1));

                //每一个点的量坊
                //行列
                int hang = Integer.parseInt(datalog[13]);
                int lie = Integer.parseInt(datalog[14]);

                String[] everyRate = codeA0New.getEveryRate().split(",");

                int hangs = 1;
                int lies = 1;

                JSONArray jsonArray1 = new JSONArray();


                for(int i = 1; i < everyRate.length+1;i++)
                {
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("position",String.valueOf(3-lies)+"-"+String.valueOf(hang+1-hangs));
                    if(lies == 2)
                    {
                        jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[hang-hangs])/10));
                    }
                    else
                    {
                        jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[(lie*hang)-hangs])/10));
                    }

                    if(i % hang == 0)
                    {
                        hangs = 1;
                        lies ++;
                    }
                    else
                    {
                        hangs ++;
                    }

                    jsonArray1.add(jsonObject2);
                }

                jsonObject.put("vehicleBoxDetailDtoList",jsonArray1.toString());

                jsonObject.put("rowNumber",lie);
                jsonObject.put("colNumber",hang);

                String sss = "jdtms";

                JSONArray jsonArray = new JSONArray();

                jsonArray.add(jsonObject);
                jsonArray.add(sss);


                String param_json = jsonArray.toString();
                String method = "jingdong.tms.data.receiveVehicleBox";
                String version ="2";
                SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String timestamp = format0.format(new Date());
                String sign = buildSign(timestamp, version, method, param_json, token, app_key, app_secret);
                System.out.println(sign);
                timestamp = URLEncoder.encode(timestamp, "utf-8");
                String url = "https://api.jdwl.com/routerjson?access_token="+token+"&app_key="+app_key+"&method="+method+"&sign="+sign+"&timestamp="+timestamp+"&v="+version+"";
                System.out.println(url);
                System.out.println(param_json);
                String response = HttpClient.post(url, param_json);
                System.out.println(response);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            codeA0New.setCheckStatus(-7);
            codeA0NewDao.save(codeA0New);
        }
    }


    //任务单toJD
//    @Scheduled(cron="0 0/59 * * * ?")
    public void checkMessionToJD(){
        //每次遍历100条
        PageRequest pageRequest = new PageRequest(0, 1000);
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndCarNumber(pageRequest, 0,"010ACJ383");
        Page<Mession> messionPage = messionDao.findByIsAnsyCarTime(pageRequest, 6);
        List<Mession> messionList = messionPage.getContent();

        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";

        for(Mession mession : messionList)
        {
            try
            {
                List<CodeA0New> codeA0NewList = codeA0NewDao.findByRateDateString(mession.getRateDataString());

                CodeA0New codeA0New = new CodeA0New();

                if(codeA0NewList != null && codeA0NewList.size() != 0)
                {
                    codeA0New = codeA0NewList.get(0);
                }

                Car car = carDao.findByCarNumberAndIsDel(mession.getCarNumber(),0);

                String[] datalog = codeA0New.getDataString().split(",");
                try
                {
                    mession.setIsAnsyCarTime(7);
                    messionDao.save(mession);

                    for(int m = 0;m<2;m++)
                    {

                        int c = (int) (89999999*Math.random()+10000000);

                        JSONObject jsonObject = new JSONObject();

                        if(m == 0)
                        {
                            jsonObject.put("type",1);
                            jsonObject.put("businessCode",c);
                            mession.setOpenNumber(String.valueOf(c));
                            messionDao.save(mession);

                            String stringDate = DateTool.Date2String(mession.getEndOpenDoorTime(),"yyyy-MM-dd HH:mm:ss");
                            jsonObject.put("gatherTime", stringDate);

                            List<CodeA2Double> codeA2Double = codeA2DoubleDao.findByCarNumberAndCreatedTime(car.getCarNumber(),mession.getEndOpenDoorTime());

                            if(codeA2Double != null && codeA2Double.size() != 0)
                            {
                                jsonObject.put("lat",codeA2Double.get(0).getLat());
                                jsonObject.put("lng",codeA2Double.get(0).getLng());
                            }
                            else
                            {
                                jsonObject.put("lat",0);
                                jsonObject.put("lng",0);
                            }

                        }
                        else
                        {
                            jsonObject.put("type",2);
                            jsonObject.put("businessCode",c);
                            mession.setCloseNumber(String.valueOf(c));
                            messionDao.save(mession);

                            String stringDate = DateTool.Date2String(mession.getStartCloseDoorTime(),"yyyy-MM-dd HH:mm:ss");
                            jsonObject.put("gatherTime", stringDate);

                            List<CodeA2Double> codeA2Double = codeA2DoubleDao.findByCarNumberAndCreatedTime(car.getCarNumber(),mession.getStartCloseDoorTime());

                            if(codeA2Double != null && codeA2Double.size() != 0)
                            {
                                jsonObject.put("lat",codeA2Double.get(0).getLat());
                                jsonObject.put("lng",codeA2Double.get(0).getLng());
                            }
                            else
                            {
                                jsonObject.put("lat",0);
                                jsonObject.put("lng",0);
                            }
                        }


                        jsonObject.put("vehicleNumber",car.getCarCnumber());

                        jsonObject.put("dataSource","23");

                        jsonObject.put("vehicleLong",Double.parseDouble(car.getLength()));
                        jsonObject.put("vehicleWidth",Double.parseDouble(car.getWidth()));
                        jsonObject.put("vehicleHeight",Double.parseDouble(car.getHeight()));

                        //计算体积
                        Double tj = (Double.parseDouble(car.getLength())*Double.parseDouble(car.getWidth())*Double.parseDouble(car.getHeight())*Double.parseDouble(mession.getRate()))/100;

                        BigDecimal b = new BigDecimal(tj);
                        double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

                        jsonObject.put("volume",String.valueOf(f1));

                        //每一个点的量坊
                        //行列
                        int hang = Integer.parseInt(datalog[13]);
                        int lie = Integer.parseInt(datalog[14]);

                        String[] everyRate = mession.getEveryRate().split(",");

                        int hangs = 1;
                        int lies = 1;

                        JSONArray jsonArray1 = new JSONArray();


                        for(int i = 1; i < everyRate.length+1;i++)
                        {
                            JSONObject jsonObject2 = new JSONObject();
                            jsonObject2.put("position",String.valueOf(3-lies)+"-"+String.valueOf(hang+1-hangs));
                            if(lies == 2)
                            {
                                jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[hang-hangs])/10));
                            }
                            else
                            {
                                jsonObject2.put("volume",String.valueOf(Double.parseDouble(everyRate[(lie*hang)-hangs])/10));
                            }

                            if(i % hang == 0)
                            {
                                hangs = 1;
                                lies ++;
                            }
                            else
                            {
                                hangs ++;
                            }

                            jsonArray1.add(jsonObject2);
                        }

                        jsonObject.put("vehicleBoxDetailDtoList",jsonArray1.toString());

                        jsonObject.put("rowNumber",lie);
                        jsonObject.put("colNumber",hang);

                        String sss = "jdtms";

                        JSONArray jsonArray = new JSONArray();

                        jsonArray.add(jsonObject);
                        jsonArray.add(sss);


                        String param_json = jsonArray.toString();
                        String method = "jingdong.tms.data.receiveVehicleBox";
                        String version ="2";
                        SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timestamp = format0.format(new Date());
                        String sign = buildSign(timestamp, version, method, param_json, token, app_key, app_secret);
                        System.out.println(sign);
                        timestamp = URLEncoder.encode(timestamp, "utf-8");
                        String url = "https://api.jdwl.com/routerjson?access_token="+token+"&app_key="+app_key+"&method="+method+"&sign="+sign+"&timestamp="+timestamp+"&v="+version+"";
                        System.out.println(url);
                        System.out.println(param_json);
                        String response = HttpClient.post(url, param_json);
                        System.out.println(response);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    mession.setIsAnsyCarTime(-7);
                    messionDao.save(mession);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                mession.setIsAnsyCarTime(-7);
                messionDao.save(mession);
            }
//            SocketLogSend socketLogSend = socketLogSendDao.findByDataStringLike(mession.getRateDataString());
        }
    }


    /**
     * 检索异常提供给京东
     */
//    @Scheduled(cron="0 0/59 * * * ?")
    public void checkYichangToJD(){

        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        //传感器异常
        PageRequest pageRequest = new PageRequest(0, 10000);
        Page<SocketLogSend> socketLogSendListPage = socketLogSendDao.findByCodeAndCheckStatus(pageRequest,"A1",8080);
        List<SocketLogSend> socketLogSendList = socketLogSendListPage.getContent();


        for(SocketLogSend socketLogSend : socketLogSendList)
        {
            socketLogSend.setCheckStatus(8089);
            socketLogSendDao.save(socketLogSend);
            if(socketLogSend.getDataString().contains("1,1,1,1,1,1,1,1,1,1,1,1,1,1"))
            {
                try {

                    String logData = socketLogSend.getDataString();

                    String[] logs = logData.split(",");

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("vehicleNumber",logs[2]);
                    jsonObject.put("exceptionType",2);
                    jsonObject.put("dataSource","23");
                    jsonObject.put("lat",Double.parseDouble(logs[8]));
                    jsonObject.put("lng",Double.parseDouble(logs[7]));
                    jsonObject.put("exceptionTime",logs[9]);
                    jsonObject.put("exceptionInfo","传感器异常");
                    jsonObject.put("businessCode",socketLogSend.getId());

                    String sss = "jdtms";

                    JSONArray jsonArray = new JSONArray();

                    jsonArray.add(jsonObject);
                    jsonArray.add(sss);

                    String param_json = jsonArray.toString();
                    String method = "jingdong.tms.data.receiveVehicleBoxException";
                    String version ="2";
                    SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String timestamp = format0.format(new Date());
                    String sign = buildSign(timestamp, version, method, param_json, token, app_key, app_secret);
                    System.out.println(sign);
                    timestamp = URLEncoder.encode(timestamp, "utf-8");
                    String url = "http://test-gateway.jdwl.com/routerjson?access_token="+token+"&app_key="+app_key+"&method="+method+"&sign="+sign+"&timestamp="+timestamp+"&v="+version+"";
                    System.out.println(url);
                    System.out.println(param_json);
                    String response = HttpClient.post(url, param_json);
                    System.out.println(response);
                    socketLogSend.setCheckStatus(8999);
                    socketLogSendDao.save(socketLogSend);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    socketLogSend.setCheckStatus(-8089);
                    socketLogSendDao.save(socketLogSend);
                }
            }
        }
    }


    /**
     * 检索离线车辆
     */
//    @Scheduled(cron="0 0/59 * * * ?")
    public void checkOutLineToJD() throws ParseException {
        String app_key ="668526a8b991490296bd437a28364f12";
        String app_secret ="b1ed8f09feb84855a41b4b038cdacd18";
        String token ="20569539d40440dfa47d45ef065923f1";


        List<SocketLogSend> socketLogSendList = socketLogSendDao.findGroupByIdAndCodeGroupByCarNumber("A4");


        for(SocketLogSend socketLogSend : socketLogSendList)
        {
            try
            {
                float plus = Float.parseFloat(TimePlus.gongshiTimePlusToSecond(new Date(),socketLogSend.getCreateTime(),1));

                if(plus > 360)
                {
                    //离线
                    String logData = socketLogSend.getDataString();

                    String[] logs = logData.split(",");

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("vehicleNumber",logs[2]);
                    jsonObject.put("exceptionType",2);
                    jsonObject.put("dataSource","23");
                    jsonObject.put("lat",Double.parseDouble(logs[8]));
                    jsonObject.put("lng",Double.parseDouble(logs[7]));
                    jsonObject.put("exceptionTime",logs[9]);
                    jsonObject.put("exceptionInfo","设备离线异常");
                    jsonObject.put("businessCode",socketLogSend.getId());

                    String sss = "jdtms";

                    JSONArray jsonArray = new JSONArray();

                    jsonArray.add(jsonObject);
                    jsonArray.add(sss);

                    String param_json = jsonArray.toString();
                    String method = "jingdong.tms.data.receiveVehicleBoxException";
                    String version ="2";
                    SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String timestamp = format0.format(new Date());
                    String sign = buildSign(timestamp, version, method, param_json, token, app_key, app_secret);
                    System.out.println(sign);
                    timestamp = URLEncoder.encode(timestamp, "utf-8");
                    String url = "http://test-gateway.jdwl.com/routerjson?access_token="+token+"&app_key="+app_key+"&method="+method+"&sign="+sign+"&timestamp="+timestamp+"&v="+version+"";
                    System.out.println(url);
                    System.out.println(param_json);
                    String response = HttpClient.post(url, param_json);
                    System.out.println(response);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }





    private static String buildSign(String timestamp, String version, String method ,

                                    String paramJson , String accessToken ,

                                    String appKey, String appSecret) throws Exception {

        //第一步，按照顺序填充参数

        Map<String, String> map = new TreeMap();

        map.put("timestamp", timestamp);

        map.put("v", version);

        map.put("method", method);

        map.put("param_json", paramJson);

        map.put("access_token", accessToken);

        map.put("app_key", appKey);



        StringBuilder sb = new StringBuilder(appSecret);

        //按照规则拼成字符串

        for (Map.Entry entry : map.entrySet()) {

            String name = (String) entry.getKey();

            String value = (String) entry.getValue();

            sb.append(name).append(value);

        }

        sb.append(appSecret);

        //MD5

        return md5(sb.toString());

    }

    public static String md5(String source) throws Exception {

        MessageDigest md = MessageDigest.getInstance("MD5");

        byte[] bytes = md.digest(source.getBytes("utf-8"));

        return byte2hex(bytes);
    }

    private static String byte2hex(byte[] bytes) {

        StringBuilder sign = new StringBuilder();

        for (int i = 0; i < bytes.length; i++) {

            String hex = Integer.toHexString(bytes[i] & 0xFF);

            if (hex.length() == 1) {

                sign.append("0");

            }
            sign.append(hex.toUpperCase());
        }

        return sign.toString();
    }
}
